package com.itheima.web.service.impl.oms;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.oms.OrderDeliveryDto;
import com.itheima.dto.oms.OrderMoneyDto;
import com.itheima.dto.oms.OrderPageDto;
import com.itheima.dto.oms.OrderReceiverDto;
import com.itheima.service.oms.IOmsOrderService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.PageResult;
import com.itheima.vo.oms.OmsOrder;
import com.itheima.vo.oms.OmsOrderItem;
import com.itheima.vo.oms.OmsOrderOperateHistory;
import com.itheima.vo.oms.OrderDetailVo;
import com.itheima.vo.ums.UmsAdmin;
import com.itheima.web.mapper.oms.OmsOrderItemMapper;
import com.itheima.web.mapper.oms.OmsOrderMapper;
import com.itheima.web.mapper.oms.OmsOrderOperateHistoryMapper;
import com.itheima.web.mapper.ums.AdminMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 王志斌
 * @since 2022-07-06
 */
@DubboService
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsOrderService {
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private OmsOrderOperateHistoryMapper omsOrderOperateHistoryMapper;
    @Autowired
    private OmsOrderItemMapper omsOrderItemMapper;


    //批量删除订单
    @Override
    public void delete(List<Integer> ids) {
        List<Long> list = ids.stream().map(id ->
                id.longValue()).collect(Collectors.toList());
        omsOrderMapper.deleteBatchIds(list);
    }

    //修改订单费用信息
    @Override
    public void updateOrderMoney(OrderMoneyDto dto) {
        Long orderId = dto.getOrderId().longValue();
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(dto, order);
        order.setId(orderId);
        order.setModifyTime(LocalDateTime.now());
        Integer count = omsOrderMapper.updateById(order);
        if (count != null) {
            UmsAdmin umsAdmin = adminMapper.selectById(3);
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(0);
            history.setNote("修改订单费用信息");
            history.setOperateMan(umsAdmin.getNickName());
            omsOrderOperateHistoryMapper.insert(history);
        }
    }

    //修改收货人信息
    @Override
    public void updateOrderReceiver(OrderReceiverDto dto) {
        Long orderId = dto.getOrderId().longValue();

        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(dto, order);
        order.setId(orderId);
        order.setModifyTime(LocalDateTime.now());
        Integer count = omsOrderMapper.updateById(order);
        if (count != null) {
            UmsAdmin umsAdmin = adminMapper.selectById(3);
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(0);
            history.setNote("修改收货人信息");
            history.setOperateMan(umsAdmin.getNickName());
            omsOrderOperateHistoryMapper.insert(history);
        }
    }

    //批量关闭
    @Override
    public void close(Map map) {
        List<Long> orderIds = new ArrayList<>();
        String idsStr = (String) map.get("ids");
        String[] split = idsStr.split(",");
        for (String id : split) {
            orderIds.add(Long.parseLong(id));
        }
        String note = (String) map.get("note");
        UmsAdmin umsAdmin = adminMapper.selectById(3);
        List<OmsOrder> orderList = omsOrderMapper.selectBatchIds(orderIds);

        Integer count = updateOrderList(orderList);
        if (count != null) {
            List<OmsOrderOperateHistory> historyList = new ArrayList<>();
            for (OmsOrder order : orderList) {
                order.setStatus(4);
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(order.getId());
                history.setCreateTime(LocalDateTime.now());
                history.setNote(note);
                history.setOrderStatus(order.getStatus());
                history.setOperateMan(umsAdmin.getNickName());
                historyList.add(history);
            }
            save(historyList);
        }
    }

    //批量发货
    @Override
    public void delivery(List<OrderDeliveryDto> list) {
        List<OmsOrder> orderList = new ArrayList<>();
        for (OrderDeliveryDto dto : list) {
            OmsOrder order = new OmsOrder();
            BeanUtils.copyProperties(dto, order);
            if (StringUtils.isNotEmpty(dto.getAddress())) {
                order.setReceiverDetailAddress(dto.getAddress());
            }
            order.setId(dto.getOrderId().longValue());
            order.setStatus(2);
            order.setDeliveryTime(LocalDateTime.now());
            orderList.add(order);
        }
        Integer count = updateOrderList(orderList);
        if (count != null) {
            UmsAdmin umsAdmin = adminMapper.selectById(3);
            List<OmsOrderOperateHistory> historyList = new ArrayList<>();
            for (OmsOrder order : orderList) {
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(order.getId());
                history.setCreateTime(LocalDateTime.now());
                history.setNote("完成发货");
                history.setOrderStatus(2);
                history.setOperateMan(umsAdmin.getNickName());
                historyList.add(history);
            }
            save(historyList);
        }
    }
//备注订单
    @Override
    public Integer note(Map<String, String> map) {
        Long orderId = Long.parseLong(map.get("id"));
        String note = map.get("note");
        Integer orderStatus = Integer.parseInt(map.get("status"));
        UmsAdmin umsAdmin = adminMapper.selectById(3);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setNote(note);
        history.setOrderStatus(orderStatus);
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan(umsAdmin.getNickName());
        return omsOrderOperateHistoryMapper.insert(history);
    }
//根据订单id查看详情
    @Override
    public OrderDetailVo findById(Integer id) {
        Long orderId = id.longValue();
        OmsOrder order = omsOrderMapper.selectById(orderId);
        List<OmsOrderOperateHistory> list = findOperateHistory(orderId);
        List<OmsOrderItem> orderItemList = findOrderItem(orderId);

        return OrderDetailVo.init(order, list, orderItemList);
    }

    @Override
    public PageResult list(OrderPageDto dto) {
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(dto, order);
        if (StringUtils.startsWith(dto.getReceiverKeyword(), "1")) {
            order.setReceiverPhone(dto.getReceiverKeyword());
        } else {
            order.setReceiverName(dto.getReceiverKeyword());
        }

        Page page = pageOrder(dto.getPageNum(), dto.getPageSize(), order);


        return PageResult.init(page.getTotal(),dto.getPageNum().longValue(), dto.getPageSize().longValue(), page.getRecords());
    }



    //批量更新订单
    public Integer updateOrderList(List<OmsOrder> orderList) {
        Integer count = null;
        for (OmsOrder order : orderList) {
            count = omsOrderMapper.updateById(order);
        }
        return count;
    }

    //批量保存订单操作历史记录
    public void save(List<OmsOrderOperateHistory> historyList) {
        for (OmsOrderOperateHistory history : historyList) {
            omsOrderOperateHistoryMapper.insert(history);
        }
    }

    //根据订单id查询订单操作历史记录
    public List<OmsOrderOperateHistory> findOperateHistory(Long orderId) {
        QueryWrapper<OmsOrderOperateHistory> qw = new QueryWrapper<>();
        qw.eq("order_id", orderId);
        return omsOrderOperateHistoryMapper.selectList(qw);
    }

    //根据订单id查询订单所包含的商品
    public List<OmsOrderItem> findOrderItem(Long orderId) {
        QueryWrapper<OmsOrderItem> qw = new QueryWrapper<>();
        qw.eq("order_id", orderId);
        return omsOrderItemMapper.selectList(qw);
    }
    //分页查询订单详情
    public Page pageOrder(Integer pageNum, Integer pageSize, OmsOrder order) {
        Page page = new Page(pageNum, pageSize);
        QueryWrapper<OmsOrder> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(order.getCreateTime())) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = format.parse(order.getCreateTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String startTime = DateUtils.getStartOfDay(date);
            String endTime = DateUtils.getEndOfDay(date);
            qw.between("create_time", startTime, endTime);
        }
        qw.eq(StringUtils.isNotEmpty(order.getOrderSn()), "order_sn", order.getOrderSn()) //订单编号
                .eq(order.getOrderType() != null, "order_type", order.getOrderType())  //订单类型
                .eq(order.getSourceType() != null, "source_type", order.getSourceType())  //订单来源
                .eq("delete_status", 0)  //删除状态：0->未删除
                .eq(order.getStatus() != null, "status", order.getStatus())//订单状态
                .like(StringUtils.isNotEmpty(order.getReceiverName()), "receiver_name", order.getReceiverName())//收货人
                .eq(StringUtils.isNotEmpty(order.getReceiverPhone()), "receiver_phone", order.getReceiverPhone())//收货人手机号码
                .orderByDesc("create_time");
        Page selectPage = omsOrderMapper.selectPage(page, qw);

        return selectPage;
    }
}
